package com.example.smartcity_poverty.ui.ItemAllService

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.ui.ItemAllService.fragment.AllMoreFragment
import com.example.smartcity_poverty.ui.ItemAllService.fragment.AllMoreFragment.Companion.moreTypeId
import com.google.android.material.tabs.TabLayoutMediator
import kotlinx.android.synthetic.main.fragment_dashboard.*
import kotlinx.coroutines.Dispatchers

/**
 * 底部导航栏 - 全部服务
 */
class ItemAllServiceFragment : Fragment() {

    // 服务类别
    var serviceClass = ArrayList<String>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_dashboard, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setTabLayoutOrViewPager2()
    }

    /**
     * 配置TabLayout 和 Viewpager2
     */
    private fun setTabLayoutOrViewPager2() = coroutine(Dispatchers.Main) {
        // 获取全部服务类别
        val result = api.getMore()

        if (result.code == 200) {
            for (i in result.rows!!) {
                serviceClass.add(i.serviceType.toString())
            }
        }

        // 消除重复的元素
        val distinct = serviceClass.distinct()
        serviceClass.clear()
        serviceClass.addAll(distinct)

        // 配置ViewPager2
        homeMoreViewPager2.adapter = object : FragmentStateAdapter(this@ItemAllServiceFragment) {
            override fun getItemCount(): Int = serviceClass.size

            override fun createFragment(position: Int): Fragment {
                return when(position) {
                    position -> AllMoreFragment()
                    else -> AllMoreFragment()
                }
            }

            override fun getItemId(position: Int): Long {
                moreTypeId = when(position) {
                    // 根据position来获取类名下标内容
                    position -> position
                    else -> throw Exception("全部服务模块出错!")
                }
                return super.getItemId(position)
            }
        }

        // 将TabLayout和Viewpager2联动起来
        TabLayoutMediator(homeMoreTabLayout, homeMoreViewPager2) {tab, position ->
            when(position) {
                position -> {
                    if (serviceClass[position] == "null") {
                        tab.text = "其他"
                    } else {
                        tab.text = serviceClass[position]
                    }

                }
            }
        }.attach()
    }
}